/*!==========================================
 图文预览模块
 提供方法：doArtSendPreview 开始预览操作(参数为图文id和图文标题)
 并且合并了未授权登录（unauthor）的模块的方法
============================================
*/
require( './style.less' );
define( [
  'require',
  'jquery',
  'constants',
  'message',
  'ajax',
  'unauthor',
  'api',
  'bootstrap'
], function( require, $, route ) {
  var returnParam = {
    articleGroup: null, // 发送的图文Id
    articleTitle: null, // 发送的图文标题
  };

  var ap = returnParam.$selector = $( '#article_preview' );
  var promitMsg = '正在预览，请留意你的手机';

  var bwAuthor = require( 'unauthor' );
  var ShowTitleMessage = require( 'message' );
  var showTime = ShowTitleMessage.showTime;
  var apis = require( 'api' ).SEND_PREVIEW;

  $.extend( returnParam, bwAuthor, {
    // 开始预览操作
    doArtSendPreview: function( artObj ) {
      $.extend( this, artObj );
      ap.modal( 'show' );
      return this;
    }
  } );

  var dataUtils = {
    gzhHtmlBuild: function( json ) {
      var html = '';
      for ( var i in json ) {

        if ( json[ i ].preview_account == null ) {
          json[ i ].preview_account = '';
        }
        if ( json[ i ].verify_type_info == -1 ) {
          html += '<div class="gzh_detail" app-ID="' + json[ i ].app_id + '" login_account="' + json[ i ].login_account + '" verify_type_info="-1" preview_account = "' + json[ i ].preview_account + '">';
        } else {
          html += '<div class="gzh_detail" app-ID="' + json[ i ].app_id + '" preview_account = "' + json[ i ].preview_account + '">';
        }
        html += '<img alt="" src="' + ( json[ i ].image || route.resPath + '/images/default_face.png' ) + '">';
        html += '<div class="gzh_msg">';
        html += '<span class="gzh_name">' + json[ i ].user_name + '</span>';
        html += '<span class="gzh_type">';
        html += '<span class="iconfont icon-dingyuehao"></span>';
        html += '<span class="gah_type_name">&nbsp;订阅号</span>';
        html += '</span></div></div>';
      }
      return html;
    },
    responseHtmlLoad: function() {

      $.post( apis.GET_SEND_PREVIEW, {}, function( data ) {

        var gzhDetail = typeof data === 'string' ? $.parseJSON( data ) : data;

        $( '.account_detail', ap ).html( dataUtils.gzhHtmlBuild( gzhDetail ) );

        var newIndex = 0;
        var maxVal = 0;
        for ( var i in gzhDetail ) {
          if ( gzhDetail[ i ].update_time > maxVal ) {
            maxVal = gzhDetail[ i ].update_time;
            newIndex = i;
          } else {
            continue;
          }
        }
        $( '.account_detail>.gzh_detail', ap ).eq( newIndex ).trigger( 'click' );

      } );
    },
    approvePreview: function( param ) {
      ap.modal( 'hide' );
      ShowTitleMessage.show( promitMsg, 5e3 );
      $.ajax( {
        type: 'post',
        url: apis.PREVIEW_ARTICLE,
        data: param,
        success: function( data ) {
          if ( data ) {
            data = eval( '(' + data + ')' );
            if ( data.ret != 99999 ) {
              ShowTitleMessage.showWarning( data.msg, showTime );
            }
          }
        }
      } );
    },
    unapprovePreview: function( param ) {
      ap.modal( 'hide' );
      ShowTitleMessage.show( promitMsg, 5e3 );
      $.ajax( {
        type: 'post',
        url: apis.PREVIEW_ARTICLE_UNATHOR,
        data: param,
        success: function( data ) {
          if ( data ) {
            data = eval( '(' + data + ')' );
            if ( data.ret != 99999 ) {
              ShowTitleMessage.showWarning( data.msg, showTime );
            }
          }
        }
      } );
    }
  };

  ap.on( 'show.bs.modal', function() {
    //$('.preview_wxnum', ap).val('');
    var gahCount = $( '.account_detail>.gzh_detail', ap ).length;
    //$('.preview_wxnum').val($('.account_selected').attr('preview_account'));
    if ( gahCount > 0 ) return;
    dataUtils.responseHtmlLoad();
  } ).on( 'hide.bs.modal', function() {
    $( '.modal-footer .ok', ap ).removeAttr( 'disabled' );
  } ).on( 'click', '.account_detail .gzh_detail', function() {
    $( this ).addClass( 'account_selected' ).siblings().removeClass( 'account_selected' );
    $( '.preview_wxnum', ap ).val( $( this ).attr( 'preview_account' ) );
  } ).on( 'click', '.modal-footer .ok', function() {
    var $this = $( this );
    var $selected = $( '.account_detail .account_selected', ap );
    var previewAccount = $.trim( $( '.preview_wxnum', ap ).val() );
    if ( !$selected.length ) {
      ShowTitleMessage.showWarning( '请先选择微信公众号!', showTime );
      return;
    }
    if ( !previewAccount ) {
      ShowTitleMessage.showWarning( '请先输入微信号！', showTime );
      return;
    } else {
      var appID = $selected.attr( 'app-ID' );
      var login_account = $selected.attr( 'login_account' );
      var verify_type_info = $selected.attr( 'verify_type_info' );
      if ( !returnParam.articleGroup ) {
        ShowTitleMessage.showWarning( '预览的图文发生错误!', showTime );
        return;
      }
      //$this.prop('disabled', 'disabled');
      if ( appID && verify_type_info != -1 ) {
        dataUtils.approvePreview( {
          'preview_name': previewAccount,
          'app_id': appID,
          'article_group': returnParam.articleGroup,
          'title': returnParam.articleTitle,
        } );
        return;
      }
      var authorData = {
        login_account: login_account,
        appid: appID
      };
      if ( !login_account ) {
        authorData.isNewAuthor = !0;
      }
      $this.prop( 'disabled', 'disabled' );
      bwAuthor.doAuthorOperate( authorData, function( data ) {
        dataUtils.unapprovePreview( {
          'preview_name': previewAccount,
          'article_group': returnParam.articleGroup,
          'login_account': data.login_account,
          'title': returnParam.articleTitle
        } );
        // 修复无法重复预览的问题
        $( '.modal-footer .ok', ap ).removeAttr( 'disabled' );
        $( '.gzh_detail.account_selected', ap ).attr( 'login_account', data.login_account );
      } );
    }
  } );

  returnParam.authorCancel = function() {
    $( '.modal-footer .ok', ap ).removeAttr( 'disabled' );
  };

  return returnParam;
} );
